<template>
  <div id="app">
    <div class="header-wrap">
      <el-form :inline="true" label-width="150px" size="medium">
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;text-align: left;padding-left:22px;">
          <el-form-item label="新增父级菜单：">
            <el-button type="primary" @click="AddParentDialog">新增</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <tree-grid
      :items='getMenuData'
      :columns='columns'
      @on-row-click='rowClick'
    ></tree-grid>
    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="url">
          <el-input v-model="addForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="父菜单" prop="name">
          <el-input v-model="getParentN" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型:" prop="isMenu">
          <el-radio v-model="addForm.isMenu" label="1">菜单</el-radio>
          <el-radio v-model="addForm.isMenu" label="2">资源</el-radio>
        </el-form-item>
        <el-form-item label="资源码" prop="code">
          <el-input v-model="addForm.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNo">
          <el-input v-model="addForm.sortNo" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="url">
          <el-input v-model="editForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="父菜单">
          <el-input v-model="editForm.parentId" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型:" prop="isMenu">
          <el-radio-group v-model="editForm.isMenu">
            <el-radio class="radio" :label="1">菜单</el-radio>
            <el-radio class="radio" :label="2">资源</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资源码" prop="code">
          <el-input v-model="editForm.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNo">
          <el-input v-model="editForm.sortNo" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click="editSubmit()" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetch, post} from '@/utils/http'
  import TreeGrid from '../../common/TreeGrid'
  export default {
    data() {
      let checkSort = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入排序号'));
        }
        setTimeout(() => {
          if (!(/^[0-9]*$/.test(value))) {
            callback(new Error('请输入数字值'));
          } else {
            callback();
          }
        }, 300);
      };
      let varIsMenu = (rule, value, callback) => {
        if(value === ''){
          callback(new Error('请选择类型'));
        }else{
          callback();
        }
      };
      let urlIsMenu = (rule, value, callback) => {
        if (value === '' && this.addForm.isMenu == '1') {
          callback(new Error('请输入菜单路径'));
        }else{
          callback();
        }
      };
      let codeIsMenu = (rule, value, callback) => {
        if(value === '' && this.addForm.isMenu == '2'){
          callback(new Error('请输入资源码'));
        }else{
          callback();
        }
      }
      return {
        getMenuData:[],//菜单数据
        columns: [
          {
            title: '菜单名称',
            key: 'name',
            sortable: true
          },
          {
            title: '图标',
            key: 'icon'
          },
          {
            title: '备注',
            key: 'remark'
          },{
            title: '标识',
            key: 'code'
          },
          {
            title: '排序',
            key: 'sortNo'
          },
          {
            title: '操作',
            type: 'action',
            actions: [{
              type: 'primary',
              text: '编辑'
            },{
              type: 'primary',
              text: '添加子级'
            },{
              type: 'danger',
              text: '删除'
            }]
          }],
        defaultProps: {
          children: 'resources',
          label: 'name'
        },
        props: {
          value: 'name',
          children: 'resources'
        },
        getParentN: '',
        //编辑拿到父级的名称，显示在编辑界面
        getParentName: '/',
        //新增界面是否显示
        addFormVisible: false,
        addLoading: false,
        addFormRules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          url: [
            { validator: urlIsMenu, trigger: 'blur' }
          ],
          isMenu: [
            { validator: varIsMenu, trigger: 'blur' }
          ],
          code: [
            { validator: codeIsMenu, trigger: 'blur' }
          ],
          sortNo: [
            { validator: checkSort, trigger: 'blur' }
          ]
        },
        //新增界面数据
        addForm: {
          createUser: '',
          name: '',
          url: '',
          id: '',
          isMenu: '',
          code: '',
          sortNo: ''
        },
        //编辑相关数据
        editFormVisible: false,//编辑界面是否显示
        editLoading: false,
        editFormRules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'}
          ],
        },
        editForm: {
          id:'',
          name: '',
          url: '',
          parentId: '',
          isMenu: '',
          code: '',
          sortNo: ''
        },
        editParentId:'',
        addParentId: '',
        checkedId:''
      }
    },
    components: {
      TreeGrid
    },
    methods: {
      AddParentDialog:function(){
        this.addFormVisible = true;
      },
      //获取菜单数据
      getMenu() {
        this.listLoading = true;
        let _this = this;
        post('/api/manager/v1/resource/find',{}).then((response) => {
          this.getMenuData = response.data;
          console.log(this.getMenuData)
          this.listLoading = false;
        }).catch(function(err) {
          console.log(err)
        });
      },
      //“编辑”“添加”按钮
      rowClick(data, index, event, text) {
        let delId = data.id
        console.log(text)
        if(text === '删除') {
          if(data.resources == ''){
            this.handleDel(delId)
          }else{
            this.$message({
              message: '请先删除子集',
              type: 'error'
            });
          }
        }
        if(text === '编辑') {
          this.editFormVisible = true;
          this.editForm = data;
          //根据父级的Id，拿到父级的名称
          if(this.editForm.parentId){
            let editParentId = this.editForm.parentId;
            for(let i = 0; i < this.getMenuData.length; i++){
              if(this.getMenuData[i].id == this.editForm.parentId){
                // this.getParentName = this.getMenuData[i].name
                this.editParentId = this.editForm.parentId
                this.editForm.parentId = this.getMenuData[i].name

                console.log(this.getParentName)
              }else{
                this.getParentName = '//'
              }
            }
          }
        }
        if(text === '添加子级') {
          this.addFormVisible = true;
          this.getParentN = data.name;
          this.addParentId = data.id;
          console.log(this.getParentN)
          this.addForm = {
            name: '',
            url: '',
            parentId: '',
            isMenu: '',
            code: '',
            sortNo: ''
          };
        }
      },
      //点击节点，获取当前节点信息
      handleCurrentClick(getMenuData, node) {
        this.checkedId = getMenuData.id
        console.log("this.checkId= ", this.checkedId);
      },
      //删除
      handleDel: function (id) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          let para = {id: id}
          console.log(para)
          post('/api/manager/v1/resource/delete',para).then((response) => {
            console.log(response);
            this.listLoading = false;
            this.$message({
              message: '删除成功',
              type: 'error'
            });
            this.getMenu();
          });
        }).catch(function(err) {
          console.log(err)
        });
      },
      //编辑结束提交
      editSubmit() {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              let para = {
                id: this.editForm.id,
                name: this.editForm.name,
                url: this.editForm.url,
                parentId: this.editParentId,
                isMenu: this.editForm.isMenu,
                code: this.editForm.code,
                sortNo: this.editForm.sortNo
              }
              para.updateUser = localStorage.getItem('userName');
              console.log(para);
              post('/api/manager/v1/resource/update',para).then((response) => {
                this.editLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getMenu();
              });
            });
          }
        });
      },
      // 添加
      addSubmit: function () {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.addLoading = true;
              let para = Object.assign({}, this.addForm);
              if(this.addParentId){
                para.parentId = this.addParentId;
              }else{
                para.parentId = '';
              }
              para.parentId = this.addParentId;
              para.createUser = localStorage.getItem('userName');
              console.log(para);
              post('/api/manager/v1/resource/add',para).then((response) => {
                this.addLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.addFormVisible = false;
                this.getMenu();
              });
            })
          }
        });
      },
    },
    mounted() {
      this.getMenu();
    },
  }
</script>

<style scoped>
  html {
    height: 100%;
    font-size: 30px;
  }

  body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  #app {
    color: #2c3e50;
    width: 100%;
    font-family: Source Sans Pro, Helvetica, sans-serif;
    text-align: center;
  }

  #app a {
    color: #42b983;
    text-decoration: none;
  }

  .header-wrap{
    height: 60px;
    padding-top: 20px;
    margin-bottom: 60px;
    background-color: #66BFBF;
    border-radius: 6px;
  }
  .logo {
    width: 100px;
    height: 100px
  }
</style>
